<template>
  <div>
    <el-dialog
      title="选择更新模块"
      :visible.sync="dialogVisible"
      width="1050px"
      :close-on-click-modal="false"
    >
      <div class="warp">
        <el-form ref="form" :model="form" label-width="120px" :rules="rules">
          <el-form-item label="计划执行时间" prop="executionTime">
            <el-date-picker
              v-model="form.executionTime"
              type="datetime"
              placeholder="选择计划执行时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="handleTimeChange"
            />
          </el-form-item>
        </el-form>
        <u-page-config
          v-model="filter"
          :getList="getList"
          :tableData="tableData"
          :tableColumn="tableColumn"
          :total="total"
          :loading="loading"
          :showFilter="false"
          :showTool="false"
          showSelection
          @handleSelectionChange="handleSelectionChange"
        >
          <template #adapterVersions="{row}">
            <el-select v-model="row.adapterVersion" placeholder="请选择版本">
              <el-option
                v-for="item in row.adapterVersions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </template>
        </u-page-config>
      </div>

      <div slot="footer" class="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit" v-loading="loading">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import UPageConfig from '@/components/uPageConfig/index'
import table from "@/mixin/uTable";
import {reqGetModuleAndDrive, reqCreateUpdatePlan} from "@/api/operationAndMonitoring/updatePlan";

export default {
  name: "ModuleUpdateSelect",
  components: {UPageConfig},
  mixins: [table],
  props: {
    value: {
      type: Boolean,
      default: false
    },
    deviceCode: {
      type: String
    },
    deviceIds: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      filter: {
        pageSize: 20,
        pageNum: 1,
        data: {}
      },
      tableData: [],
      tableColumn: [
        {label: "模块名称", prop: "moduleName"},
        {label: "模块编码", prop: "moduleCode"},
        {label: "驱动名称", prop: "driveName"},
        {label: "驱动编码", prop: "driveCode"},
        {label: "驱动版本", prop: "adapterVersions", type: "slot", slot: 'adapterVersions'},
      ],
      form: {
        executionTime: null,
      },
      rules: {
        executionTime: {required: true, message: '选择计划执行时间', trigger: 'blur'}
      },
      loading: false,
      selectionData: []
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        return this.$emit('input', val)
      }
    },
    // 运维人员下拉框数据
    operationUserOptions() {
      return this.$store.state.device.operationUserOptions || []
    },
  },
  methods: {
    handleTimeChange(value){
      const current =  Date.now();
      const timeValue = new Date(value).valueOf();
      if(timeValue < current){
        this.form.executionTime = undefined;
        this.$modal.msgError('计划更新时间不能小于当前时间');
      }
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid && this.checkVersionNoEmpty()) {
          // 驱动列表
          const updateList = this.selectionData.map(item => {
            return {
              adapterName: item.adapterName,
              adapterVersion: item.adapterVersion,
              driveCode: item.driveCode,
              driveName: item.driveName,
            }
          })
          const params = this.deviceIds.map(deviceId => {
            return {
              deviceId,
              updateList,
              executionTime: this.form.executionTime
            }
          })
          // console.log("请求参数", params);
          reqCreateUpdatePlan(params).then((response) => {
            this.$modal.msgSuccess("更新计划创建成功");
            this.$router.push({
              name: 'UpdatePlan',
              query: {
                updateList: 1
              }
            })
            this.dialogVisible = false;
          }).finally(() => {
            this.loading = false;
          });
        } else {
          console.log("不通过")
          return false
        }
      });
    },
    // 检查已勾选的模块版本是否有填写
    checkVersionNoEmpty() {
      if(!this.selectionData.length) return this.$modal.msgWarning(`请勾选需要更新的模块！`)
      const result = this.selectionData.every((item, index) => {
        return Boolean(item.adapterVersion);
      })
      if (!result) this.$modal.msgWarning(`请将已勾选模块的驱动版本补充完整！`)
      return result
    },
    handleSelectionChange(selection) {
      this.selectionData = selection;
    },
    /**
     * @function getInit 分页请求
     * @param request  分页请求函数
     * @param options  默认参数
     * */
    async getInit(request, options = {}) {
      let res = null
      if (request instanceof Function) {
        let params = this.getListRequestParams();
        // console.log(params, 'list請求參數')
        this.loading = true
        try {
          res = await request({
            ...params,
            ...options
          })
          this.tableData = res.rows.map(item => {
            // 添加一个当前选择版本参数
            item.adapterVersion = null;
            return item
          });
          this.total = res.total;
          return res
        } finally {
          this.loading = false
        }
      } else {
        res = request
      }
    },
    /** 查询设备模块列表 */
    getList() {
      this.getInit(reqGetModuleAndDrive, {
        deviceCode: this.deviceCode
      })
    },
  },
  watch: {
    value: {
      handler(newValue) {
        /* if (newValue) {
          // 清空选项
          this.workOrdersList = [];
          this.formArray.find(item => item.key === 'moduleCode').options = [];
          this.form = JSON.parse(JSON.stringify(this.defaultForm));
          if(this.deviceData) this.fillDeviceIdAndGetModel();
        }else {
          this.$refs.uFormRef.reset();
        }
      }*/
      }
    },
  },
  created() {

  }
}
</script>

<style lang="scss" scoped>
.warp {
  max-height: 60vh;
  overflow: auto;
}

.form-item-wrap {
  display: flex;
}

.footer {
  width: 100%;
  text-align: right;
  margin-top: 15px;
}
</style>
